﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Data;
using CommonLib.ComMon;

namespace CommonLib.OfficeReport
{
    public class WordReprot
    {
        private int Templete_id;
        private string TempleteFile;
        private string Option;
        private string RootPath;
        private int Template_Type;  //1-word ; 2-excel
        

        /// <summary>
        /// 根据模板产生报表文件
        /// </summary>
        /// <param name="WordFile"></param>
        /// <param name="Report_id"></param>
        /// <param name="ReportDataParam"></param>
        /// <returns></returns>
        public static int GenerateReportByTemplete(string WordFile, int Report_id, string[,] ReportDataParam)
        {
            if (!File.Exists(WordFile))
                return -1;

            int pre_data_id, i;
            DataTable tmpTable=null;
            object FindText, ReplaceWith, Replace;
            object MissingValue = Type.Missing;
            object ofile = WordFile;
            Word.Bookmark BM = null;
            string oldText, newText;
            DataTable ReportItem = null;

            Word.Application WordApp = new Word.ApplicationClass();
            WordApp.DisplayAlerts = Word.WdAlertLevel.wdAlertsNone; //避免WORD所有的警告信息
            Word.Document WordDoc = WordApp.Documents.Open(ref ofile, 
                                                           ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, ref MissingValue,
                                                           ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, ref MissingValue,
                                                           ref MissingValue, ref MissingValue, ref MissingValue,ref MissingValue, ref MissingValue);
            
            Replace = Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。

                                                       * wdReplaceNone - 不替换找到的任何项。

                                                       * wdReplaceOne - 替换找到的第一项。

                                                       * */
            //this.WordDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置

            try
            {
                //替换标志字


                ReportItem = CommonLib.BLL.UR_REPORTPARAMS.GetList("Template_id=" + Report_id.ToString() + " and parameter_type<>3", "dataset_id,Param_Name").Tables[0];
                pre_data_id = -1;
                for (i = 0; i < ReportItem.Rows.Count; i++)
                {
                    if (pre_data_id != int.Parse(ReportItem.Rows[i]["dataset_id"].ToString())) //需要获取数据集
                    {
                        pre_data_id = int.Parse(ReportItem.Rows[i]["dataset_id"].ToString());
                        tmpTable = CommonLib.BLL.BS_DATASET_SQL.GetDataSetBySqlParam(pre_data_id, ReportDataParam);
                    }

                    oldText = ReportItem.Rows[i]["T_Param_Name"].ToString();//要查找的文本
                    newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ReportItem.Rows[i]["datarow"].ToString()), 
                                                           ReportItem.Rows[i]["Field_Name"].ToString()).ToString();

                    if (int.Parse(ReportItem.Rows[i]["parameter_type"].ToString())==0) //标志字参数

                    {
                        if (int.Parse(ReportItem.Rows[i]["repeat_num"].ToString()) != 0)
                            newText = CommonLib.ComMon.StringCommon.FillEqualLengthString(int.Parse(ReportItem.Rows[i]["repeat_num"].ToString()), newText, ' ', 1);
                        FindText = oldText;//要查找的文本
                        ReplaceWith = newText;//替换文本
                        WordDoc.Content.Find.Text = oldText;
                        WordDoc.Content.Find.Execute(
                            ref FindText, ref MissingValue,
                            ref MissingValue, ref MissingValue,
                            ref MissingValue, ref MissingValue,
                            ref MissingValue, ref MissingValue, ref MissingValue,
                            ref ReplaceWith, ref Replace,
                            ref MissingValue, ref MissingValue,
                            ref MissingValue, ref MissingValue);
                        InsetLogTable("替换标志字-" + oldText + " -> " + newText);
                    }
                    else if (int.Parse(ReportItem.Rows[i]["parameter_type"].ToString()) == 1) //书签参数,替换书签
                    {
                        if (WordDoc.Bookmarks.Exists(oldText))
                        {
                            FindText = oldText;
                            BM = WordDoc.Bookmarks.get_Item(ref FindText);
                            BM.Select();
                            oldText = BM.Range.Text;
                            newText = StringCommon.FillEqualLengthString(oldText, newText, ' ', 1);
                            BM.Range.Text = newText;
                            InsetLogTable("替换书签-" + oldText + " -> " + newText);
                        }
                    }
                    else //域参数替换

                    {
                    }

                }

                //处理表格,注意下标从1开始

                ReportItem = CommonLib.BLL.UR_REPORTPARAMS.GetList("Template_id=" + Report_id.ToString()+" and parameter_type=3", "dataset_id,Param_Name").Tables[0];
                if (ReportItem.Rows.Count > 0) //存在表格替换的项
                {
                    pre_data_id = -1;
                    foreach (Word.Table wdTable in WordDoc.Tables)
                    {
                        int[,,] maxcell = new int[wdTable.Rows.Count+1, wdTable.Columns.Count+1,2];
                        for (int j = 1; j <= wdTable.Rows.Count; j++)
                        {
                            for (int k = 1; k <= wdTable.Columns.Count; k++)
                            {
                                maxcell[j, k, 0] = j > 1 ? maxcell[j - 1, k, 0] + 1 : j;
                                maxcell[j, k, 1] = k > 1 ? maxcell[j, k - 1, 1] + 1 : k;
                                //为解决有的表格进行了单元格合并，使读取发生异常

                                try { oldText = wdTable.Cell(maxcell[j, k, 0], maxcell[j, k, 1]).Range.Text; }
                                catch { oldText = ""; }
                                i = 0;
                                DataRow[] ItemRow = ReportItem.Select("T_Param_Name='" + CommonLib.ComMon.StringCommon.TrimESCChar(oldText) + "'");
                                if (ItemRow.Length > 0)
                                {
                                    InsetLogTable("处理表格项－" + oldText );
                                    //打开数据集

                                    if (pre_data_id != int.Parse(ItemRow[0]["dataset_id"].ToString())) //需要获取数据集
                                    {
                                        pre_data_id = int.Parse(ItemRow[0]["dataset_id"].ToString());
                                        tmpTable = CommonLib.BLL.BS_DATASET_SQL.GetDataSetBySqlParam(pre_data_id, ReportDataParam);
                                    }
                                    switch (int.Parse(ItemRow[0]["repeat_type"].ToString()))
                                    {
                                        case 0: //不循环


                                            newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ItemRow[0]["datarow"].ToString()),
                                                           ItemRow[0]["Field_Name"].ToString()).ToString();
                                            wdTable.Cell(maxcell[j, k, 0], maxcell[j, k, 1]).Range.Text = newText;
                                            break;
                                        case 1://行循环

                                            for (i = 0; i < int.Parse(ItemRow[0]["repeat_num"].ToString()) && int.Parse(ItemRow[0]["datarow"].ToString()) + i < tmpTable.Rows.Count; i++)
                                            {
                                                //在固定的可循环的行范围内
                                                if (i < int.Parse(ItemRow[0]["fix_reprat_num"].ToString()))
                                                {
                                                    newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ItemRow[0]["datarow"].ToString()) + i,
                                                                   ItemRow[0]["Field_Name"].ToString()).ToString();
                                                    wdTable.Cell(maxcell[j, k, 0]+i, maxcell[j, k, 1]).Range.Text = newText;
                                                }
                                                //超出了固定的可循环的行范围，out_operate＝0停止循环，out_operate＝1，插入表格的方式继续循环
                                                else if (int.Parse(ItemRow[0]["out_operate"].ToString()) > 0)
                                                {
                                                    object beforeRow = wdTable.Rows[maxcell[j, k, 0]+i];
                                                    wdTable.Rows.Add(ref beforeRow);
                                                    newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ItemRow[0]["datarow"].ToString()) + i,
                                                                   ItemRow[0]["Field_Name"].ToString()).ToString();
                                                    wdTable.Cell(maxcell[j, k, 0]+i, maxcell[j, k, 1]).Range.Text = newText;
                                                    maxcell[j, k, 0] = maxcell[j, k, 0]+i;
                                                }

                                            }
                                            break;
                                        case 2: //列循环

                                            for (i = 0; i < int.Parse(ItemRow[0]["repeat_num"].ToString()) && int.Parse(ItemRow[0]["datarow"].ToString()) + i < tmpTable.Rows.Count; i++)
                                            {
                                                //在固定的可循环的行范围内
                                                if (i < int.Parse(ItemRow[0]["fix_reprat_num"].ToString()))
                                                {
                                                    newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ItemRow[0]["datarow"].ToString()) + i,
                                                                   ItemRow[0]["Field_Name"].ToString()).ToString();
                                                    wdTable.Cell(maxcell[j, k, 0], maxcell[j, k, 1]+i).Range.Text = newText;
                                                }
                                                //超出了固定的可循环的行范围，out_operate＝0停止循环，out_operate＝1，插入表格的方式继续循环
                                                else if (int.Parse(ItemRow[0]["out_operate"].ToString()) > 0)
                                                {
                                                    object beforeCol = wdTable.Columns[maxcell[j, k, 1] + i];
                                                    wdTable.Columns.Add(ref beforeCol);
                                                    newText = DataCommon.GetDataTableCell(tmpTable, int.Parse(ItemRow[0]["datarow"].ToString()) + i,
                                                                   ItemRow[0]["Field_Name"].ToString()).ToString();
                                                    wdTable.Cell(maxcell[j, k, 0], maxcell[j, k, 1]+i).Range.Text = newText;
                                                    maxcell[j, k, 0]= maxcell[j, k, 1]+i;
                                                }
                                            }
                                            break;
                                        default:
                                            break;
                                    }

                                }
                            }
                        }
                    }

                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                //执行结束，不管是否发生异常，文件保存
                WordDoc.SaveAs(ref ofile, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
                WordDoc.Close(ref MissingValue, ref MissingValue, ref MissingValue);
                //最后退出word
                WordApp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
            }

            return 1;
        }



        public static int InsetLogTable(string s)
        {
            //仅做调试用，需建表create table tmplog (logtime datetime,log varchar(1000))
            //DBUtility.dbCommon.ExecSqlCommand("insert into tmplog values('"+System.DateTime.Now.ToString()+"','"+s+"')");
            return 0;
        }

        public static int InsertRow(System.Data.DataTable tbl, string name, Int32 type)
        {
            DataRow row = null;
            if (tbl.Select("ItemName='" + name + "'").Length <= 0)
            {
                row = tbl.NewRow();
                row["ItemName"] = name;
                row["ItemType"] = type;
                tbl.Rows.Add(row);
                return 1;
            }
            return 0;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="WordFile"></param>
        /// <param name="Report_id"></param>
        /// <returns></returns>
        public static System.Data.DataTable SearchWordReportParameter(string WordFile, int Report_id)
        {
            if (!File.Exists(WordFile))
                return null;

            int pre_data_id, i;
            DataTable tmpTable = null;
            object FindText, ReplaceWith, Replace;
            object MissingValue = Type.Missing;
            object ofile = WordFile;
            Word.Bookmark BM = null;
            string oldText, newText;
            DataTable ReportItem =  new DataTable();
            
            ReportItem.TableName = "ReportItem";
            ReportItem.Columns.Add("ItemName", Type.GetType("System.String"));
            ReportItem.Columns.Add("ItemType", Type.GetType("System.Int32"));
            DataRow row = null;



            Word.Application WordApp = new Word.ApplicationClass();
            Word.Document WordDoc = WordApp.Documents.Open(ref ofile,
                                                           ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                                                           ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue,
                                                           ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);

            try
            {
                object findMatchWildcards = true;

                foreach (Word.Table wdTable in WordDoc.Tables)
                {
                    for (int j = 1; j <= wdTable.Rows.Count; j++)
                    {
                        for (int k = 1; k <= wdTable.Columns.Count; k++)
                        {
                            try
                            {
                                oldText = CommonLib.ComMon.StringCommon.TrimESCChar(wdTable.Cell(j, k).Range.Text);
                            }
                            catch
                            {
                                oldText = "";
                            }

                            if (oldText.Trim()!="" && oldText.Substring(0, 1) == "〔" && oldText.Substring(oldText.Length - 1, 1) == "〕")
                            {
                                InsertRow(ReportItem, oldText, 3);
                            }
                            
                        }
                    }
                }
                Word.Range SearchRange = WordDoc.Content;
                SearchRange.Find.Text = "〔*〕";
                SearchRange.Find.MatchWildcards = true;
                while (true)
                {
                    SearchRange.Find.Text = "〔*〕";
                    SearchRange.Find.MatchWildcards = true;
                    if (SearchRange.Find.Execute(
                        ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue,
                        ref MissingValue, ref MissingValue))
                    {
                        InsertRow(ReportItem, SearchRange.Text, 0);
                    }
                    else
                        break;
                }

                for (i = 1; i <= WordDoc.Bookmarks.Count; i++)
                {
                    object aa = i;
                    BM = WordDoc.Bookmarks.get_Item(ref aa);
                    InsertRow(ReportItem, BM.Name, 1);

                }
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
            finally
            {
                WordDoc.Saved = false;
                WordDoc.Close(ref MissingValue, ref MissingValue, ref MissingValue);
                //最后退出word
                WordApp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
            }
            return ReportItem;
        }




        ///测试过程
        public static string CreateWordFile(string CheckedInfo)
        {

            //this.oDoc.Content.Find.Text = strOldText;
            //object FindText, ReplaceWith, Replace;// 
            //object MissingValue = Type.Missing;
            //FindText = strOldText;//要查找的文本
            //ReplaceWith = strNewText;//替换文本
            //Replace = Word.WdReplace.wdReplaceAll;/**//*wdReplaceAll - 替换找到的所有项。

            //                                          * wdReplaceNone - 不替换找到的任何项。

            //                                        * wdReplaceOne - 替换找到的第一项。

            //                                        * */
            //this.oDoc.Content.Find.ClearFormatting();//移除Find的搜索文本和段落格式设置
            //if (this.oDoc.Content.Find.Execute(
            //    ref FindText, ref MissingValue,
            //    ref MissingValue, ref MissingValue,
            //    ref MissingValue, ref MissingValue,
            //    ref MissingValue, ref MissingValue, ref MissingValue,
            //    ref ReplaceWith, ref Replace,
            //    ref MissingValue, ref MissingValue,
            //    ref MissingValue, ref MissingValue))
            //{
            //    return true;
            //}
            //return false;


            string message = "";
            try
            {
                Object MissingValue = System.Reflection.Missing.Value;
                Directory.CreateDirectory("C:/CNSI");  //创建文件所在目录

                string name = "CNSI_.doc";
                object filename = "C://CNSI//" + name;  //文件保存路径
                //创建Word文档
                Word.Application WordApp = new Word.ApplicationClass();
                Word.Document WordDoc = WordApp.Documents.Add(ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);

                //添加页眉
                WordApp.ActiveWindow.View.Type = Word.WdViewType.wdOutlineView;
                WordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekPrimaryHeader;
                WordApp.ActiveWindow.ActivePane.Selection.InsertAfter("[页眉内容]");
                WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;//设置右对齐

                WordApp.ActiveWindow.View.SeekView = Word.WdSeekView.wdSeekMainDocument;//跳出页眉设置

                WordApp.Selection.ParagraphFormat.LineSpacing = 15f;//设置文档的行间距
                

                //移动焦点并换行

                object count = 14;
                object WdLine = Word.WdUnits.wdLine;//换一行;
                 WordApp.Selection.MoveDown(ref WdLine, ref count, ref MissingValue);//移动焦点
                 WordApp.Selection.TypeParagraph();//插入段落

                 //文档中创建表格

                 Word.Table newTable = WordDoc.Tables.Add(WordApp.Selection.Range, 12, 3, ref MissingValue, ref MissingValue);
                 //设置表格样式
                 newTable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleThickThinLargeGap;
                 newTable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle;
                 newTable.Columns[1].Width = 100f;
                 newTable.Columns[2].Width = 220f;
                 newTable.Columns[3].Width = 105f;

                 //填充表格内容
                 newTable.Cell(1, 1).Range.Text = "产品详细信息表";
                 newTable.Cell(1, 1).Range.Bold = 2;//设置单元格中字体为粗体

                 //合并单元格

                 newTable.Cell(1, 1).Merge(newTable.Cell(1, 3));
                 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;//垂直居中
                 WordApp.Selection.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphCenter;//水平居中
                        
                 //填充表格内容
                 newTable.Cell(2, 1).Range.Text = "产品基本信息";
                 newTable.Cell(2, 1).Range.Font.Color = Word.WdColor.wdColorDarkBlue;//设置单元格内字体颜色
                 //合并单元格

                 newTable.Cell(2, 1).Merge(newTable.Cell(2, 3));
                 WordApp.Selection.Cells.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                  //填充表格内容
                  newTable.Cell(3, 1).Range.Text = "品牌名称：";
                  newTable.Cell(3, 2).Range.Text = "sdfdsf";
                  //纵向合并单元格

                  newTable.Cell(3, 3).Select();//选中一行

                  object moveUnit = Word.WdUnits.wdLine;
                  object moveCount = 5;
                  object moveExtend = Word.WdMovementType.wdExtend;
                   WordApp.Selection.MoveDown(ref moveUnit, ref moveCount, ref moveExtend);
                   WordApp.Selection.Cells.Merge();
                   //插入图片
                   string FileName = "f:/c.jpg";//图片所在路径

                   object LinkToFile = false;
                   object SaveWithDocument = true;
                   object Anchor = WordDoc.Application.Selection.Range;
                   WordDoc.Application.ActiveDocument.InlineShapes.AddPicture(FileName, ref LinkToFile, ref SaveWithDocument, ref Anchor);
                    WordDoc.Application.ActiveDocument.InlineShapes[1].Width = 100f;//图片宽度
                    WordDoc.Application.ActiveDocument.InlineShapes[1].Height = 100f;//图片高度
                    //将图片设置为四周环绕型

                    Word.Shape s = WordDoc.Application.ActiveDocument.InlineShapes[1].ConvertToShape();
                    s.WrapFormat.Type = Word.WdWrapType.wdWrapSquare;
                        
                    newTable.Cell(12, 1).Range.Text = "产品特殊属性";
                    newTable.Cell(12, 1).Merge(newTable.Cell(12, 3));
                     //在表格中增加行

                     WordDoc.Content.Tables[1].Rows.Add(ref MissingValue);
                      
                     WordDoc.Paragraphs.Last.Range.Text = "文档创建时间：" + DateTime.Now.ToString();//“落款”

                     WordDoc.Paragraphs.Last.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;

                    //文件保存
                    WordDoc.SaveAs(ref filename, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue, ref MissingValue);
                    WordDoc.Close(ref MissingValue, ref MissingValue, ref MissingValue);
                    WordApp.Quit(ref MissingValue, ref MissingValue, ref MissingValue);
                    message=name+"文档生成成功，以保存到C:CNSI下";
            }
            catch
            {
                message = "文件导出异常！";
            }
            return message;
        }

    }
}


